package com.lbj.mall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.lbj.mall.common.entity.vo.SkuUpVo;
import com.lbj.mall.search.config.ElasticSearchConfig;
import com.lbj.mall.search.constant.ESConstant;
import com.lbj.mall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public boolean saveProduct(List<SkuUpVo> skuUpList) throws IOException {
        // 1.给ES中建立好索引，建立好映射关系
        // 2.开始保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuUpVo item : skuUpList) {
            // 设置Index索引
            IndexRequest index = new IndexRequest(ESConstant.INDEX_PRODUCT);
            // 添加id，如果不添加则会默认生成
            index.id(item.getSkuId().toString());
            String json = JSON.toJSONString(item);
            // 添加数据，使用JSON数据，并指定类型
            index.source(json, XContentType.JSON);
            bulkRequest.add(index);
        }
        // 批量保存数据，会抛出异常
        BulkResponse response = client.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        boolean hasFailures = response.hasFailures();
        if (hasFailures) {
            List<String> collect = Arrays.stream(response.getItems())
                    .map(BulkItemResponse::getId).collect(Collectors.toList());
            log.error("商家商品失败，失败的商品id为：{}", collect);
        }
        return !hasFailures;
    }
}
